import React from 'react';
import { Popup, ListView, Tabs, List, WingBlank, Button, Toast } from 'antd-mobile';
import _ from 'lodash';
import moment from 'moment';
import { fetchCoupon, fetchCouponCode } from '../../services/vipService';
import styles from './CouponCode.less';
import CouponBarcode from './CouponBarcode';

const TabPane = Tabs.TabPane;

class CouponCodeItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      infoExpand: false,
      cType: '1'
    };
  }

  onClickBarcode = (code, top) => {
    // 弹出层，展示优惠券条形码
    Popup.show(<CouponBarcode code={code} />, {
      onMaskClose: () => {
        window.scrollTo(0, top);
      },
    });
  }

  render() {
    const { type, coupon = {}, couponCode = {}, showSend, showBarcode, disableSend, onSend } = this.props;
    const isHyb = (!coupon.systemVersion || coupon.systemVersion == 'hyb');
    const couponTitle = coupon.couponTitle
    const renderValue = () => {
      let result = 0;
      if (coupon.couponType === 1) {
        result = coupon.value1;
      } else if (coupon.couponType === 2) {
        result = coupon.value2;
      } else if (coupon.couponType === 3) {
        result = coupon.value2;
      } else if (coupon.couponType === 4) {
        result = '';
      }

      if (!isHyb) {
        result = couponCode.giftMoney;
      }

      return result;
    };
    const renderCondition1 = () => {
      let result = '无门槛使用';
      if (coupon.couponType === 1) {
        //
      } else if (coupon.couponType === 2) {
        result = `满${coupon.value1 || 0}可用`;
      } else if (coupon.couponType === 3) {
        result = `满${coupon.value1 || 0}可用`;
      }
      return result;
    };
    const renderCondition2 = () => {
      let result = '不限品类';
      if (coupon.applyItems && coupon.applyItems.length) {
        result = '限';
        if (coupon.applyType === 1) {
          result += '品类';
        } else if (coupon.applyType === 2) {
          result += '品牌';
        } else if (coupon.applyType === 3) {
          result += '商品';
        }
      }
      return result;
    };

    // 优惠券标题
    const renderCodeInfo1Head = () => {
        let result = coupon.couponTitle;

        if (coupon.couponType === 1) {
          result = `${coupon.value1}元现金券`;
        } else if (coupon.couponType === 2) {
          result = `满减券：满${coupon.value1}元减${coupon.value2}元`;
        } else if (coupon.couponType === 3) {
          result = `满赠券：满${coupon.value1}元赠${coupon.value2}元`;
        } else if (coupon.couponType === 4) {
          result = '福利券';
        }
        return result
    };

    // 优惠券使用说明
    const renderExtraInfo1 = () => {
      let result = '全场通用';
      if (coupon.applyType && coupon.applyItems && coupon.applyItems.length) {
        result = '限';
        if (coupon.applyType === 1) {
          result += '品类：';
        } else if (coupon.applyType === 2) {
          result += '品牌：';
        } else if (coupon.applyType === 3) {
          result += '商品：';
        }
        result += '仅限';
        result += _.map(coupon.applyItems, (item) => item.label).join('、');
        result += '（特价商品除外）';
      }
      return result;
    };

    
    const renderExtraInfo2 = () => {
      return coupon.useRules ? `使用规则：${coupon.useRules}` : '';
    };

    // 优惠券使用时间
    const renderCodeInfo2 = () => {
      let result = '';
      if (coupon.startDate && coupon.endDate) {
        result += `${moment(coupon.startDate).format('YYYY.MM.DD')}至${moment(coupon.endDate).format('YYYY.MM.DD')}`;
      } else if (coupon.startDate || coupon.endDate) {
        result += `${moment(coupon.startDate || coupon.startDate).format('YYYY.MM.DD')}`;
      } else if (coupon.expireType === 2 && coupon.expireDays) {
        const startDate = couponCode.effectiveDate || couponCode.createdAt;
        const endDate = moment(startDate).add(+coupon.expireDays, 'day');
        result += `${moment(startDate).format('YYYY.MM.DD')}至${moment(endDate).format('YYYY.MM.DD')}`;
      } else {
        result += '-';
      }

      if (!isHyb) {
        result = `${moment(couponCode.startDate).format('YYYY.MM.DD')}至${moment(couponCode.endDate).format('YYYY.MM.DD')}`;
      }

      return result;
    };

   
    const renderCodeInfo3 = () => {
      let result = '';
      if (couponCode.code) {
        couponCode.code.split('').forEach((val, index) => {
          if (index % 4 === 0) {
            result += ' ';
          }
          result += val;
        });
        return `券码：${result}`;
      }
    };
    const renderCodeInfo4 = () => {
      return '详细信息';
    };
    const renderCurrency = () => {
      return coupon.couponType === 4 ? <span>福利券</span> : <span>¥&nbsp;</span>;
    };
    const toggleInfo = () => {
      this.setState({
        infoExpand: !this.state.infoExpand,
      });
    };

    let itemClass = 'couponCodeItem';
    if (type === 3) {
      itemClass += ' couponCodeExpireItem';
    }
    if (type === 2) {
      itemClass += ' couponCodeUsedItem';
    }
    if (this.state.infoExpand) {
      itemClass += ' couponCodeExpandItem';
    }

    const cType = this.props.cType
    return (
      <div className="couponCodeItemWrap">
        <div className={itemClass} style={{
          background: cType == '2' && 'url(' +require('../../assets/vipcard/coupon/coupon_bg2_new.png')+ ') no-repeat 0 0',
        }}>
         {/*  <div className="couponCodeHead">
            <div className="couponCodeValue">
              <span className="couponCodeValue1">{renderCurrency()}</span>
              <span className="couponCodeValue2">{renderValue()}</span>
            </div>
          </div> */}

          <div className="couponCodeBody">
            <div className="couponCodeInfo1">
              <div className="couponCodeInfo1Head">
                {cType == '2' ? '' :renderCodeInfo1Head() }
              </div>
            </div>
            <div 
              className="couponCodeContent"
              style={cType == '2' ? {
                position: 'absolute',
                top: '.990338rem',
                left: '1.642512rem',
                padding: 0
              } : {}}
            >{couponTitle}</div>
            {cType == '2' && (<span className="leftName">优惠券</span>)}
            <div className="couponCodeInfo2">
              <div className="useTime">{cType == '2' ? '' : renderCodeInfo2() }</div>
              <div className="useRules">{cType == '2' ? '' : '使用说明：' + renderExtraInfo1()}</div>
            </div>


            {/* 券码 */}
            {/* <div className="couponCodeInfo3">{renderCodeInfo3()}</div> */}

            {/* 2021/2/20 change */}
            {/* <div className="couponCodeInfo4">{renderCodeInfo4()}<span onClick={() => toggleInfo()} className="couponCodeInfoIcon"></span></div> */}
            {/* {showSend && <div className="couponCodeSendBtn">
              <Button disabled={disableSend} size="small" onClick={() => { onSend(coupon); }} type="primary" inline className={styles.sendBtn}>{disableSend ? '已发券' : '发券'}</Button>
            </div>}
            {showBarcode && <div className="couponCodeBarcode" onClick={(event) => {
              const doc = document.documentElement;
              const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
              this.onClickBarcode(couponCode.code, top);
            }}>
            </div>} */}
          </div>
        </div>

        {this.state.infoExpand && (
          <div className="couponCodeExtraInfo">
            <div className="couponCodeExtraInfo1">{renderExtraInfo1()}</div>
            <div className="couponCodeExtraInfo2">{renderExtraInfo2()}</div>
          </div>
        )}
      </div>
    );
  }
}

CouponCodeItem.propTypes = {
  type: React.PropTypes.number,
  coupon: React.PropTypes.object,
  couponCode: React.PropTypes.object,
  onSend: React.PropTypes.func,
  showSend: React.PropTypes.bool,
  showBarcode: React.PropTypes.bool,
};

class CouponCode extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      codeData1: { data: [], meta: {} },
      codeData2: { data: [], meta: {} },
      codeData3: { data: [], meta: {} },
      couponMap: {},
      cType: '1'
    };
  }

  errorToast = (msg) => {
    Toast.hide();
    Toast.fail(`${msg || '网络异常'}，请退出会员卡再重新进入`, 5);
  }

  componentDidMount() {
    Toast.loading('加载优惠券信息...', 30);
    const { shopId, card_id, card_no } = this.props;
    if (shopId && (card_id || card_no)) {
      fetchCoupon(shopId, { pageSize: 500, filter: { card_id: card_id || card_no, status: { $in: [1, 2, 3] } } }).then((data) => {
        const coupons = data.data;
        console.log('优惠券信息', coupons)
        if (coupons && coupons.length) {
          this.setState({
            couponMap: _.reduce(coupons, (result, item) => {
              result[item.couponId] = item;
              return result;
            }, {}),
          });
        }
      }, (e) => {
        console.error('componentDidMount fetchCoupon error', e);
        this.errorToast();
      });

      fetchCouponCode(shopId, { pageSize: 20, filter: { card_id: card_id || card_no, status: 1 } }).then((data) => {
        const codes = data.data;
        if (codes && codes.length) {
          this.setState({
            codeData1: data,
          });
        }
        Toast.hide();
      }, (e) => {
        console.error('componentDidMount fetchCouponCode error', e);
        this.errorToast();
      });
    } else {
      this.errorToast('会员信息获取失败');
    }
  }

  onChange = (key) => {
    this.setState({
      cType: key
    })
    const { shopId, card_id, card_no } = this.props;
    if (shopId && (card_id || card_no)) {
      const stateKey = 'codeData' + key;
      const oldData = this.state[stateKey] || {};
      const pageNum = oldData.meta ? oldData.meta.page + 1 : 1;
      const params = { page: pageNum, pageSize: 20, filter: { card_id: card_id || card_no, status: parseInt(key, 10) } };
      fetchCouponCode(shopId, params).then((data) => {
        const { meta: { page } } = data;
        const state = {};
        if (page > 1) {
          state[stateKey] = {
            meta: { ...oldData.meta, ...data.meta },
            data: [...oldData.data, ...data.data],
          };
        } else {
          state[stateKey] = data;
        }
        this.setState(state);
      }, (e) => {
        console.error('componentDidMount fetchCouponCode error', e);
      });
    }
  }

  render() {
    const hasMore = (type) => {
      const stateKey = `codeData${type}`;
      const { meta: { page = 1, totalPageCount = 1 } } = this.state[stateKey];
      return page < totalPageCount;
    };
    const dataSource1 = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    const dataSource2 = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    const dataSource3 = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    const renderRow1 = (rowData, sectionID, rowID) => {
      return (
        <CouponCodeItem cType={this.state.cType} showSend={!!this.props.showSend} showBarcode={!!this.props.showBarcode} type={1} couponCode={rowData} coupon={this.state.couponMap[rowData.couponId]} />
      );
    };
    const renderRow2 = (rowData, sectionID, rowID) => {
      return (
        <CouponCodeItem cType={this.state.cType} type={2} couponCode={rowData} coupon={this.state.couponMap[rowData.couponId]} />
      );
    };
    const renderRow3 = (rowData, sectionID, rowID) => {
      return (
        <CouponCodeItem cType={this.state.cType} type={3} couponCode={rowData} coupon={this.state.couponMap[rowData.couponId]} />
      );
    };
    // 没有优惠券的时候展示
    const renderEmpty = () => {
      return (<div className="emptyCouponList">
        <div className="emptyCoupon"></div>
        <div className="emptyText">暂无该类优惠券</div>
      </div>);
    };

    /* 未使用 */
    const renderList1 = () => {
      if (!this.state.codeData1.data.length) {
        return renderEmpty();
      }
      return (<ListView
       // 在上一次数据的基础上多增加
        dataSource={dataSource1.cloneWithRows(this.state.codeData1.data)}
        renderRow={renderRow1}
        renderSeparator={null}
        renderFooter={() => <div
          style={{ padding: 10, textAlign: 'center' }}
          onClick={() => { this.onChange(1); }}
        >
          {!hasMore(1) ? '' : '下一页'}
        </div>}
        // 首屏10条数据
        initialListSize={20}
        // 每次循环渲染的数据条数
        pageSize={20}
        // 距离底部200px触发
        scrollRenderAheadDistance={200}
        scrollEventThrottle={20}
        // 滚动框为body，不用手动设置height
        useBodyScroll
        style={{ marginBottom: -10 }}
      />);
    };

    /* 已使用 */
    const renderList2 = () => {
      if (!this.state.codeData2.data.length) {
        return renderEmpty();
      }
      return (<ListView
        dataSource={dataSource2.cloneWithRows(this.state.codeData2.data)}
        renderRow={renderRow2}
        renderSeparator={null}
        renderFooter={() => <div
          style={{ padding: 10, textAlign: 'center' }}
          onClick={() => { this.onChange(2); }}
        >
          {!hasMore(2) ? '' : '下一页'}
        </div>}
        initialListSize={20}
        pageSize={20}
        scrollRenderAheadDistance={200}
        scrollEventThrottle={20}
        useBodyScroll
        style={{ marginBottom: -10 }}
      />);
    };

    /* 已过期 */
    const renderList3 = () => {
      if (!this.state.codeData3.data.length) {
        return renderEmpty();
      }
      return (<ListView
        dataSource={dataSource3.cloneWithRows(this.state.codeData3.data)}
        renderRow={renderRow3}
        renderSeparator={null}
        renderFooter={() => <div
          style={{ padding: 10, textAlign: 'center' }}
          onClick={() => { this.onChange(3); }}
        >
          {!hasMore(3) ? '' : '下一页'}
        </div>}
        initialListSize={20}
        pageSize={20}
        scrollRenderAheadDistance={200}
        scrollEventThrottle={20}
        useBodyScroll
        style={{ marginBottom: -10 }}
      />);
    };

    return (
      <div className="couponCodeWrap">
        <div>
          <Tabs defaultActiveKey="1" onChange={this.onChange}>
            <TabPane tab={"未使用"} key="1">
              <WingBlank>
                {renderList1()}
              </WingBlank>
            </TabPane>
            <TabPane tab={"已使用"} key="2">
              <WingBlank>
                {renderList2()}
              </WingBlank>
            </TabPane>
            <TabPane tab={"已过期"} key="3">
              <WingBlank>
                {renderList3()}
              </WingBlank>
            </TabPane>
          </Tabs>
        </div>
      </div>
    );
  }
}

CouponCode.propTypes = {
  shopId: React.PropTypes.string,
  card_id: React.PropTypes.string,
  card_no: React.PropTypes.string,
  showBarcode: React.PropTypes.bool,
};

class CouponCodeList extends React.Component {
  render() {
    const { couponCodeList = [], couponList = [] } = this.props;
    const couponMap = _.reduce(couponList, (result, coupon) => {
      result[coupon.couponId] = coupon;
      return result;
    }, {});

    let filterCodeList = couponCodeList;
    filterCodeList = _.filter(filterCodeList, (coupon) => {
      let result = true;
      if (coupon.status != 1) {
        result = false;
      }
      return result;
    });

    return (
      <div className="couponCodeWrap">
        <List renderHeader={() => <div>共{filterCodeList.length}条</div>} className="couponList">
          {filterCodeList.map((couponCode) => {
            return (
              <CouponCodeItem key={couponCode.couponId + couponCode.code} coupon={couponMap[couponCode.couponId]} couponCode={couponCode} />
            );
          })}
        </List>
      </div>
    );
  }
}

CouponCodeList.propTypes = {
  couponList: React.PropTypes.array,
  couponCodeList: React.PropTypes.array,
};

class CouponList extends React.Component {
  render() {
    const { taskType, user, couponList = [], onSend, couponCodeList = [] } = this.props;
    let filterCouponList = couponList;
    filterCouponList = _.filter(filterCouponList, (coupon) => {
      let result = true;
      if (coupon.sendType != 3) {
        result = false;
      }
      if (coupon.systemVersion && coupon.systemVersion !== 'hyb') {
        result = false;
      }
      if (coupon.status != 1) {
        result = false;
      }
      return result;
    });

    if (user && filterCouponList.length) {
      const branchNo = user.branchNo || user.branchId;
      if (branchNo) {
        filterCouponList = _.filter(filterCouponList, (coupon) => {
          let result = true;
          if (coupon.useScope && coupon.useScope.branches && coupon.useScope.branches.length) {
            if (!_.includes(coupon.useScope.branches, branchNo)) {
              result = false;
            }
          }
          return result;
        });
      }
    }

    if (!_.isNil(taskType) && filterCouponList.length) {
      filterCouponList = _.filter(filterCouponList, (coupon) => {
        let result = true;
        if (coupon.useScope && coupon.useScope.tasks && coupon.useScope.tasks.length) {
          if (!_.includes(coupon.useScope.tasks, '' + taskType)) {
            result = false;
          }
        }
        return result;
      });
    } else if (_.isNil(taskType) && filterCouponList.length) {
      filterCouponList = _.filter(filterCouponList, (coupon) => {
        let result = true;
        if (coupon.useScope && coupon.useScope.tasks && coupon.useScope.tasks.length) {
          result = false;
        }
        return result;
      });
    }

    const todayCouponIds = [];
    const today = moment().format('YYYY-MM-DD');
    _.forEach(couponCodeList, (couponCode) => {
      const date = moment(couponCode.createdAt).format('YYYY-MM-DD');
      if (couponCode.status === 1 && date === today) {
        todayCouponIds.push(couponCode.couponId);
      }
    });
    const onItemSend = (val) => {
      if (onSend) {
        onSend(val);
      }
    };
    return (
      <div className="couponCodeWrap">
        <List renderHeader={() => <div>共{filterCouponList.length}条</div>} className="couponList">
          {filterCouponList.map((coupon) => {
            return (
              <CouponCodeItem
                showSend
                disableSend={_.includes(todayCouponIds, coupon.couponId)}
                onSend={onItemSend}
                key={coupon.shopId + coupon.couponId}
                coupon={coupon}
              />
            );
          })}
        </List>
      </div>
    );
  }
}

CouponList.propTypes = {
/*   couponList: React.PropTypes.array,
  onSend: React.PropTypes.func,
  user: React.PropTypes.object,
  taskType: React.PropTypes.string, */
};

// CouponList.defaultProps = {
// };

export default CouponCode;
export { CouponCodeItem, CouponList, CouponCodeList };
